# -*- codeing = utf-8 -*-
import re
import docx
import openpyxl
from docx import Document
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, colors, Side
import PySimpleGUI as sg


def turn(wordPath, excelPath):
    # 原始word文件和要生成的Excel文件
    fn_word = Document(wordPath)
    fn_excel = excelPath

    # 创建空白Excel文件，获取第一个空白工作表
    wb = Workbook()
    ws = wb.worksheets[0]

    ws.append(['一级功能', '二级功能', '三级功能', '四级功能', '五级功能', '六级功能', '七级功能', '八级功能', '九级功能', '正文 :'])

    ws.column_dimensions["A"].width = 15
    ws.column_dimensions["B"].width = 15
    ws.column_dimensions["C"].width = 15
    ws.column_dimensions["D"].width = 15
    ws.column_dimensions["E"].width = 15
    ws.column_dimensions["F"].width = 15
    ws.column_dimensions["G"].width = 15
    ws.column_dimensions["H"].width = 15
    ws.column_dimensions["I"].width = 15
    ws.column_dimensions["J"].width = 65
    first2, first3, first4, first5, first6, first7, first8, first9 = 1, 1, 1, 1, 1, 1, 1, 1
    # 遍历word文件中的所有段落文本
    for p in fn_word.paragraphs:
        # 删除段落文本两侧的空白字符
        txt = p.text.rstrip()
        # 直接跳过空行
        if not txt:
            continue

        # 添加为一级标题
        if p.style.name == 'Heading 1':
            ws.append([txt, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '])
            first2 = 1
        # 添加为二级标题
        elif p.style.name == 'Heading 2':
            if first2 == 1:
                # 第一个二级目录，不添加新行，直接和一级目录写在同一行
                list(ws.rows)[-1][1].value = txt
                first2 = first2 + 1
            elif first2 > 1:
                # 新增一行添加为二级标题
                ws.append(['', txt, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '])
            first3 = 1
        # 添加为三级标题
        elif p.style.name == 'Heading 3':
            if first3 == 1:
                # 第一个三级目录，不添加新行，直接和二级写在同一行
                list(ws.rows)[-1][2].value = txt
                first3 = first3 + 1
            elif first3 > 1:
                # 新增一行添加为三级目录
                ws.append(['', '', txt, ' ', ' ', ' ', ' ', ' ', ' ', ' '])
            first4 = 1
        # 添加为四级标题
        elif p.style.name == 'Heading 4':
            if first4 == 1:
                # 第一个四级目录，不添加新行，直接和三级写在同一行
                list(ws.rows)[-1][3].value = txt
                first4 = first4 + 1
            elif first4 > 1:
                # 新增一行添加为四级目录
                ws.append(['', '', '', txt, ' ', ' ', ' ', ' ', ' ', ' '])
            first5 = 1
        # 添加为五级标题
        elif p.style.name == 'Heading 5':
            if first5 == 1:
                # 第一个五级目录，不添加新行，直接和四级写在同一行
                list(ws.rows)[-1][4].value = txt
                first5 = first5 + 1
            elif first5 > 1:
                # 新增一行添加为五级目录
                ws.append(['', '', '', '', txt, ' ', ' ', ' ', ' ', ' '])
            first6 = 1
        # 添加为六级标题
        elif p.style.name == 'Heading 6':
            if first6 == 1:
                # 第一个六级目录，不添加新行，直接和五级写在同一行
                list(ws.rows)[-1][5].value = txt
                first6 = first6 + 1
            elif first6 > 1:
                # 新增一行添加为六级目录
                ws.append(['', '', '', '', '', txt, ' ', ' ', ' ', ' '])
            first7 = 1
        # 添加为七级标题
        elif p.style.name == 'Heading 7':
            if first7 == 1:
                # 第一个七级目录，不添加新行，直接和六级写在同一行
                list(ws.rows)[-1][6].value = txt
                first7 = first7 + 1
            elif first7 > 1:
                # 新增一行添加为七级目录
                ws.append(['', '', '', '', '', '', txt, ' ', ' ', ' '])
            first8 = 1
        # 添加为八级标题
        elif p.style.name == 'Heading 8':
            if first8 == 1:
                # 第一个八级目录，不添加新行，直接和七级写在同一行
                list(ws.rows)[-1][7].value = txt
                first8 = first8 + 1
            elif first8 > 1:
                # 新增一行添加为八级目录
                ws.append(['', '', '', '', '', '', '', txt, ' ', ' '])
            first9 = 1
        # 添加为八级标题
        elif p.style.name == 'Heading 9':
            if first9 == 1:
                # 第一个九级目录，不添加新行，直接和八级写在同一行
                list(ws.rows)[-1][8].value = txt
                first9 = first9 + 1
            elif first9 > 1:
                # 新增一行添加为九级目录
                ws.append(['', '', '', '', '', '', '', '', txt, ' '])

    # 设置单元格边框
    side = Side(border_style='thin',
                color=colors.BLACK)

    for row in ws.rows:
        for cell in row:
            cell.border = Border(top=side, bottom=side,
                                 left=side, right=side)

    start1, start2, start3, start4, start5, start6, start7, start8, start9 = 1, 1, 1, 1, 1, 1, 1, 1, 1
    for index, row in enumerate(ws.rows, start=1):
        # 合并第一列的指定单元格，水平左对齐，垂直居中对齐
        if row[0].value:
            if index > start1:
                ws.merge_cells(f'A{start1}:A{index - 1}')
                ws[f'A{start1}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start1 = index
        # 合并第二列的指定单元格，水平左对齐，垂直居中对齐
        if row[1].value:
            if index > start2:
                ws.merge_cells(f'B{start2}:B{index - 1}')
                ws[f'B{start2}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start2 = index
        # 合并第三列的指定单元格，水平左对齐，垂直居中对齐
        if row[2].value:
            if index > start3:
                ws.merge_cells(f'C{start3}:C{index - 1}')
                ws[f'C{start3}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start3 = index
        # 合并第四列的指定单元格，水平左对齐，垂直居中对齐
        if row[3].value:
            if index > start4:
                ws.merge_cells(f'D{start4}:D{index - 1}')
                ws[f'D{start4}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start4 = index
        # 合并第五列的指定单元格，水平左对齐，垂直居中对齐
        if row[4].value:
            if index > start5:
                ws.merge_cells(f'E{start5}:E{index - 1}')
                ws[f'E{start5}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start5 = index
        # 合并第六列的指定单元格，水平左对齐，垂直居中对齐
        if row[5].value:
            if index > start6:
                ws.merge_cells(f'F{start6}:F{index - 1}')
                ws[f'F{start6}'].alignment = Alignment(horizontal='center',
                                                       vertical='center',
                                                       wrap_text=True)
            start6 = index
        # 合并第七列的指定单元格，水平左对齐，垂直居中对齐
        if row[6].value:
            if index > start7:
                ws.merge_cells(f'G{start7}:G{index - 1}')
            ws[f'G{start7}'].alignment = Alignment(horizontal='center',
                                                   vertical='center',
                                                   wrap_text=True)
            start7 = index
        # 合并第八列的指定单元格，水平左对齐，垂直居中对齐
        if row[7].value:
            if index > start8:
                ws.merge_cells(f'H{start8}:H{index - 1}')
            ws[f'H{start8}'].alignment = Alignment(horizontal='center',
                                                   vertical='center',
                                                   wrap_text=True)
            start8 = index
        # 合并第九列的指定单元格，水平左对齐，垂直居中对齐
        if row[8].value:
            if index > start9:
                ws.merge_cells(f'I{start9}:I{index - 1}')
            ws[f'I{start9}'].alignment = Alignment(horizontal='center',
                                                   vertical='center',
                                                   wrap_text=True)
            start9 = index


    if index > start1:
        ws.merge_cells(f'A{start1}:A{index}')
        ws[f'A{start1}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start2:
        ws.merge_cells(f'B{start2}:B{index}')
        ws[f'B{start2}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start3:
        ws.merge_cells(f'C{start3}:C{index}')
        ws[f'C{start3}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start4:
        ws.merge_cells(f'D{start4}:D{index}')
        ws[f'D{start4}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start5:
        ws.merge_cells(f'E{start5}:E{index}')
        ws[f'E{start5}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start6:
        ws.merge_cells(f'F{start6}:F{index}')
        ws[f'F{start6}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start7:
        ws.merge_cells(f'G{start7}:G{index}')
        ws[f'G{start7}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start8:
        ws.merge_cells(f'H{start8}:H{index}')
        ws[f'H{start8}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)

    if index > start9:
        ws.merge_cells(f'I{start9}:I{index}')
        ws[f'I{start9}'].alignment = Alignment(horizontal='center',
                                               vertical='center',
                                               wrap_text=True)
    wb.save(fn_excel)

    wwbb = openpyxl.load_workbook(fn_excel)
    sheet = wwbb.active

    def get_title(fn_excel):
        wwbb = openpyxl.load_workbook(fn_excel)
        sheet = wwbb.active
        for i in range(2, sheet.max_row + 1):
            for j in range(9, 1, -1):
                judge = sheet.cell(row=i, column=j).value
                if judge == ' ':
                    continue
                else:
                    yield judge
                    break
    file = docx.Document(wordPath)
    content = ''
    for para in file.paragraphs:
        content = content + para.text.strip()
        if 'Heading' in para.style.name:
            content = content + 'Heading'
    title = list(get_title(fn_excel))
    for data in range(len(title)):
        try:
            if data == len(title) - 1:
                res = content.split(title[data] + 'Heading')[1]
            else:
                res = content.split(title[data] + 'Heading')[1].split(title[data + 1] + 'Heading')[0].split('Heading')[0]
            sheet.cell(row=data + 2, column=10).value = res
            sheet[f'J{data}'].alignment = Alignment(horizontal='left',
                                                    vertical='center',
                                                    wrap_text=True)
        except:
            continue

    wwbb.save(fn_excel)

event, values = sg.Window('W2E',
                          [[sg.Text('Word源文件选择:')],
                           [sg.Input(), sg.FileBrowse(file_types=(("Text Files", "*.docx"),))],
                           [sg.Text('Excel目标文件地址:')],
                           [sg.Input(), sg.FolderBrowse('Browse')],
                           [sg.Text('Excel目标文件名:')],
                           [sg.InputText('demo.xlsx')],
                           [sg.OK('确定'), sg.Cancel('取消')]]).Read()


if values[0] == '':
    sg.popup_auto_close('请输入Word源文件地址，请重新打开程序')
if values[1] == '':
    sg.popup_auto_close('请输入Excle目标文件地址，请重新打开程序')
if event == '确定':
    wordFilePath = values[0]
    excelFilePath = values[1] + "/" + values[2]
    if re.findall("(?i).+?\\.(xlsx)", values[2]):
        sg.popup_auto_close('程序运行结束，窗口自动关闭，稍安勿躁')
        turn(wordFilePath, excelFilePath)
    else:
        sg.popup_auto_close('文件名后缀请以.xlsx结尾,请重新打开程序')
elif event == '取消':
    print()